// pages/newPersonVerify/index.js
import { checkMediaAuth } from '../../utils/cameraUtil.js'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    noAuthorizeTips: "摄像头权限请求中",
    hasAuth: false,  //是否有相机和录音权限
    isFont: true,
    canTakeVideo: false, //控制按钮是否可以点击，防止用户快速点击出现问题
    longVideoTimeout: 4,
    isTakingVideo: false,
    ctx: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //设置camera的context
    this.setData({
      ctx: wx.createCameraContext()
    })
    this.options = options
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //初次授权、用户到设置中授权后重新发起授权
    this.getCameraAuth()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 获取摄像头权限
   */
  getCameraAuth: function() {
    checkMediaAuth((camera, record) => {
      if(camera && record) {
        this.setData({
          noAuthorizeTips: '摄像头、录音权限获取成功',
          hasAuth: true,
          canTakeVideo: true,
        })
      } else if(camera) {
        this.setData({
          noAuthorizeTips: '摄像头权限获取成功、未获取录音权限'
        })
      } else {
        this.setData({
          noAuthorizeTips: '摄像头、录音权限获取失败'
        })
      }
    })
  },
  // 摄像头转换
  switchCameraTap () {
    this.setData({
      isFont: !this.data.isFont,
    })
  },
  initCameraDone() {
    console.log('initCameraDone')
  },
  //用户不允许使用摄像头时触发
  initCameraError: function() {
    this.setData({
      noAuthorizeTips: '摄像头打开失败，请查看是否开启权限',
      hasAuth: false,
    })
  },

  /**
   * 拍摄视频
   */
  takeVideoTap: function() {
    //设置按钮不可点击
    this._setCanTakeVideo(false)

    var taking = !this.data.isTakingVideo
    var that = this;
    wx.showLoading({
      title: taking ? '开始录像中' : '结束录像中',
    })

    if (!taking) {
      //用户点击停止录像
      this.stopRecord()
      return
    }

    this.data.ctx.startRecord({
      success: (res) => {
        that.timeInterval()
        wx.hideLoading()
        //只录制1秒就点击结束，通常会导致录像失败
        setTimeout(function() {
          that._setCanTakeVideo(true)
        }, 2000)
      },
      timeoutCallback: (res) => {
        //超过30s或页面 onHide 时会结束录像
        console.log(that.isHide, "---------超过30s或页面 onHide 时会结束录像", res)
        if (!that.isHide && !that.data.isShortVideoType) {
          that._dealVideo(res)
        }
      },
      fail: (res) => {
        wx.hideLoading()
        wx.showToast({
          title: '开始录像失败',
          icon: 'none'
        })
        that._setCanTakeVideo(true)
      },
    })
  },

  /**
   * 停止录像
   */
  stopRecord: function(e) {
    this._setCanTakeVideo(false)

    if (this._IntervalNumber != null) {
      clearInterval(this._IntervalNumber)
    }
    var that = this;
    this.data.ctx.stopRecord({
      success: (res) => {
        //res.tempThumbPath\tempVideoPath
        console.log(res)
        this._dealVideo(res)
      },
      fail: (res) => {
        wx.hideLoading()
        wx.showToast({
          title: '结束录像失败',
          icon: 'none'
        })
        console.log("stop fail", res)
        that._setCanTakeVideo(true)
      },
      complete: (res) => {
        console.log("stop complete", res)
        that.setData({
          isTakingVideo: false,
        })
      }
    })
  },

  /**
   * 倒计时
   */
  timeInterval: function() {
    if (this._IntervalNumber != null) {
      clearInterval(this._IntervalNumber)
    }
    //时间初始化
    this.setData({
      isTakingVideo: true,
      longVideoTimeout: 4
    })
    var that = this;
    //赋值number，用于清除
    this._IntervalNumber = setInterval(function() {
      var time = --that.data.longVideoTimeout;
      if (time <= 0) {
        clearInterval(that.number)
        that.stopRecord()
      }
      that.setData({
        longVideoTimeout: time
      })
    }, 1000);
  },
  /**设置摄像按钮是否可以点击 */
  _setCanTakeVideo: function(enable) {
    this.setData({
      canTakeVideo: enable
    })
  },
  /**
   * 处理视频
   */
  _dealVideo: function(res) {
    this.setData({
      isTakingVideo: false,
      canTakeVideo: false
    })
    wx.showToast({
      title: '视频录制结束',
      icon: 'none'
    })
    //短视频
    // this._uploadeShortVideo(res)
  },
  /**
   * 上传短视频
   */
  _uploadeShortVideo: function(video) {
    let that = this
    wx.showLoading({
      title: '正在上传中...',
    })
    // wx.uploadFile({
    //   url: obj.baseApi() + '/api/sign/liveBodyVideoUpload',
    //   name: 'file',
    //   filePath: video.tempVideoPath,
    //   header: {
    //     "Content-Type": "multipart/form-data",
    //     'user-token-header': app.getToken(),
    //     'sign-token-header': wxRequest.defaults.header['sign-token-header'],
    //     'sign-person-id-header': wxRequest.defaults.header['sign-person-id-header']
    //   },
    //   formData,
    //   success: (res) => {
    //     wx.hideLoading()
    //     let data = JSON.parse(res.data) //返回的res.data数据是json字符串
    //     if (data.success) {
    //       simpleToast('上传成功')
    //       const {returnObject} = data
    //       //登录
    //       let userId = returnObject.tokenInfo.userId
    //       wx.setStorageSync(storageKey.userId, userId)
    //       wx.setStorageSync(storageKey.isLoginForFace, userId)
    //       app.globalData.userCardInfo = null
    //       app.globalData.userInfo = returnObject.tokenInfo
    //       app.globalData.userInfo.orgLegalName = returnObject.userType == '2' ? '' : returnObject.subjectAuth
    //       wxRequest.defaults.header['sign-person-id-header'] = that.data.personId
    //       //设置token
    //       wxRequest.defaults.header['user-token-header'] = app.getToken()
    //       wxRequest.getRequest(`/api/user/userInfo.do?userId=${userId}`, {})
    //       .then(res => {
    //         if (!res.success) return;
    //         wx.setStorageSync(storageKey.isLogin, true)
    //         app.globalData.userInfo = Object.assign(app.globalData.userInfo, res.data.result)
    //       })
    //     }

    //     that._toNext(data) //使用外层的that提示
    //     that._setCanTakeVideo(true)
    //   },
    //   fail(err) {
    //     wx.hideLoading()
    //     setTimeout(function () {
    //       simpleToast("上传失败,请重试")
    //     }, 500)
    //     that._setCanTakeVideo(true)
    //   }
    // })
  },
  _toNext (data) {
    this._setCanTakeVideo(true)
    const {success, message, errorCode, returnObject} = data
    let nextStep = success ? returnObject.step.nextStep : ''
    // wx.redirectTo({
    //   url: '/pages/newPersonVerify/result?success=' + success + '&message=' + message + '&errorCode=' + errorCode + '&nextStep=' + nextStep + '&personId=' + this.data.personId,
    // })
  }
})